package com.wangxiaonan.wxwork.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.wxwork.exeption.ServiceException;
import com.wangxiaonan.wxwork.service.MessageService;
import com.wangxiaonan.wxwork.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class MessageServiceImpl implements MessageService {
    private static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);

    @Override
    public JSONObject sendMessage(String token, String jsonParam) {
        logger.info("[MessageServiceImpl] sendMessage >>>>>>>>>>>>>>>>");
        if (StringUtils.isBlank(token) || StringUtils.isBlank(jsonParam)) {
            logger.error("[MessageServiceImpl] sendMessage >> token: {}", token);
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        String result;
        try {
            String url = String.format(MessageService.POST_MESSAGE_SEND_URL, token);
            result = HttpUtil.post(url, jsonParam);
        } catch (IOException e) {
            throw new ServiceException("connect_refuse", "接口请求失败");
        }
        JSONObject json;
        try {
            json = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("[MessageServiceImpl] sendMessage >> result: {}", result);
            throw new ServiceException("object_format_error", "请求结果格式化错误");
        }

        return json;
    }
}
